/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tandaica0612
 */
public class HttpPostToAWebSite {

    public HttpPostToAWebSite() {
        try {
            /*
             * Code này sẽ post dữ liệu đến server localhost
             * Nhưng sẽ không login thành công vì ở server , sau khi login thì server sẽ redirect to other url lên connect không login thành công
             * */
            URL url = new URL("http://localhost/www/tandaica0612%27s%20blog/index.php?action=login");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String datapost = "username=tandaica0612&password=toilatoi&remember=on&login=Login";
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            /*
            Map<String, List<String>> map = conn.getRequestProperties();
            Set<Map.Entry<String, List<String>>> entrysets = map.entrySet();
            for (Map.Entry<String, List<String>> entry : entrysets) {
                String headerName = entry.getKey();
                System.out.println("Header Name:" + headerName);
                List<String> headerValues = entry.getValue();
                for (String value : headerValues) {
                  System.out.print("Header value:" + value);
                }
                System.out.println();
                System.out.println();
            }
             * */
            conn.connect();
            PrintWriter writer = new PrintWriter(conn.getOutputStream());
            writer.write(datapost);
            writer.flush();
            writer.close();
            // Get the response
            for(int i=0;i<conn.getHeaderFields().size();i++){
                System.out.print("Key : "+ conn.getHeaderFieldKey(i) + "Value : "+ conn.getHeaderField(i) + "\n");
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            Logger.getLogger(HttpPostToAWebSite.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /*
    public static void main(String args[]){
        new HttpPostToAWebSite();
    }
     * **/
}
